<?php
require_once("lib/api.php");
require_once("res/const.php");
require_once("lib/auth/session.php");
$api = new api();

if (!loggedIn()) {
	$api->setYouFail("Not logged in.");
} elseif (isset($_POST['content']) && isset($_POST['subject']) && isset($_POST['rating'])) {
	$content = filter_var($_POST['content'], FILTER_SANITIZE_STRING); // strips tags, gets plaintext
	if (!(strlen($content) < $MAX_LENGTH_CONTENT)) {
		$api->setYouFail("Content needs to be shorter than $MAX_LENGTH_CONTENT characters.");
	} elseif (!(strlen($content) > $MIN_LENGTH_CONTENT)) {
		$api->setYouFail("Content needs to be longer than $MIN_LENGTH_CONTENT characters.");
	} else {
		$subject = filter_var($_POST['subject'], FILTER_SANITIZE_STRING); // strips tags, gets plaintext
		if (!(strlen($subject) < $MAX_LENGTH_SUBJECT)) {
			$api->setYouFail("Subject needs to be shorter than $MAX_LENGTH_SUBJECT characters.");
		} elseif (!(strlen($subject) > $MIN_LENGTH_CONTENT)) {
			$api->setYouFail("Subject needs to be longer than $MIN_LENGTH_SUBJECT characters.");
		} else {
			$rating = $_POST['rating'];
			if (!(is_int($rating) || ctype_digit($rating))) {
				$api->setYouFail("Rating needs to be an integer.");
			} elseif (!(($rating >= $MIN_RATING) && ($rating <= $MAX_RATING))) {
				$api->setYouFail("Rating needs to be ranging from $MIN_RATING to $MAX_RATING.");
			} else {
				if (isset($_POST['img']) && (strlen($_POST['img']) > 0)) {
					if (!filter_var($_POST['img'], FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED)) {
						$api->setYouFail("Image field needs a proper URL.");
					} else {
						$img = $_POST['img'];
						require_once("lib/post/create.php");
						$postid = createPost($subject, $content, $rating, $img);
						$api->setOK();
						$api->setReturn("postid", $postid);
					}
				} else {
					require_once("lib/post/create.php");
					$postid = createPost($subject, $content, $rating, "");
					$api->setOK();
					$api->setReturn("postid", $postid);
				}
			}
		}
	}
} else {
	$api->setYouFail("Content, subject and rating needs to be provided.");
}
$api->returnResponse();

?>
